package com.example.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.demo.dto.BalanceDto;
import com.example.demo.dto.FoodDto;
import com.example.demo.entity.*;
import com.example.demo.mapper.BalanceFoodRelationMapper;
import com.example.demo.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Atanycosts
 * @description 针对表【balance_food_relation】的数据库操作Service实现
 * @createDate 2023-04-03 22:56:29
 */
@Scope("prototype")
@Service
public class BalanceFoodRelationServiceImpl extends ServiceImpl<BalanceFoodRelationMapper, BalanceFoodRelation>
        implements BalanceFoodRelationService {

    @Autowired
    @Lazy
    private BalanceFoodRelationService balanceFoodRelationService;
    /**
     * 方案
     */
    @Autowired
    private BalanceService balanceService;

    /**
     * 食物联系表
     */
    @Autowired
    private FoodtvrelationService foodtvrelationService;

    /**
     * 食物
     */
    @Autowired
    private FoodService foodService;

    /**
     * 维生素
     */
    @Autowired
    private VitaminService vitaminService;

    /**
     * 微量元素
     */
    @Autowired
    private TraceService traceService;


    @Autowired
    private BalanceFoodRelationMapper balanceFoodRelationMapper;

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteBalanceFoodRelation(Long id) {
        balanceService.removeById(id);
    }

    /**
     * 已复查
     * 保存方案
     * 完成
     *
     * @param balanceDto
     */
    @Override
    public void saveBalance(BalanceDto balanceDto) {
        //保存balanceFoddrelation
        //保存后就有ID了
        balanceService.saveBatch(balanceDto.getBalances());

        //找到刚保存的
        LambdaQueryWrapper<Balance> balanceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        balanceLambdaQueryWrapper.orderByDesc(Balance::getUpdateTime).last("limit 1");
        Balance one = balanceService.getOne(balanceLambdaQueryWrapper);
        //得到BalanceID
        Long id = one.getId();
        //得到最终balanceDVRelationID
        // final Long[] saveRelationID = new Long[1];
        List<FoodDto> foodDto = balanceDto.getFoodDto();
        int size = foodDto.size();
        foodDto = foodDto.stream().map((item) -> {
            BalanceDto savaDto = new BalanceDto();
            //balance_food_relation存入balance_ID
            savaDto.setBalanceId(id);
            savaDto.setFoodId(String.valueOf(item.getId()));
            this.save(savaDto);
            // saveRelationID[0] = savaDto.getId();
            return item;
        }).collect(Collectors.toList());
    }

    /**
     * 更新方案
     *
     * @param balanceDto
     */
    @Override
    public void updateBalance(BalanceDto balanceDto) {
        //不需要去更改Trace和Vitamin
        //只需要更改BalanceFoodRelation这张表就行
        //先通过ID更新balanceFoodRelation里的数据
        Long balanceId = balanceDto.getBalanceId();
        UpdateWrapper<BalanceFoodRelation> balanceFoodRelationUpdateWrapper = new UpdateWrapper<>();
        balanceFoodRelationUpdateWrapper.eq("balance_id", balanceId);
        balanceFoodRelationMapper.delete(balanceFoodRelationUpdateWrapper);

        List<FoodDto> foodDto = balanceDto.getFoodDto();
        foodDto = foodDto.stream().map((item) -> {
            balanceDto.setBalanceId(balanceId);
            balanceDto.setFoodId(String.valueOf(item.getId()));
            this.save(balanceDto);
            return item;
        }).collect(Collectors.toList());
        balanceService.updateBatchById(balanceDto.getBalances());

    }

    /**
     * 根据id查询方案 , 传过来的是BalanceID
     *
     * @param id
     * @return
     */
    @Override
    public BalanceDto getByIdBalance(Long id) {
        //通过同一个方案ID找到food
        QueryWrapper<BalanceFoodRelation> balanceFoodRelationLambdaQueryWrapper = new QueryWrapper<>();
        balanceFoodRelationLambdaQueryWrapper.like("balance_id", id);
        List<BalanceFoodRelation> list1 = balanceFoodRelationService.list(balanceFoodRelationLambdaQueryWrapper);
        BalanceFoodRelation balanceFoodRelation = list1.get(0);
        Long balanceFoodRelationId = balanceFoodRelation.getId();

        //传过来的是Relation的ID
        BalanceFoodRelation byId = this.getById(balanceFoodRelationId);

        //返回的值
        BalanceDto balanceDto = new BalanceDto();
        BeanUtils.copyProperties(byId, balanceDto);

        //拿到balance数据

        Balance balanceList = balanceService.getById(id);

        //封装
        balanceDto.setBalances(Collections.singletonList(balanceList));

        //通过同一个方案ID找到food
        // LambdaQueryWrapper<BalanceFoodRelation> balanceFoodRelationLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        // balanceFoodRelationLambdaQueryWrapper2.eq(BalanceFoodRelation::getBalanceId, byId.getBalanceId());
        // //比如说找到了4个 拿到对应的food_id
        // List<BalanceFoodRelation> list = balanceFoodRelationService.list(balanceFoodRelationLambdaQueryWrapper2);
        List<String> foodIdList = list1.stream()
                .map(BalanceFoodRelation::getFoodId)
                .collect(Collectors.toList());
        //转成Long
        List<Long> collect = foodIdList.stream().map(Long::parseLong).collect(Collectors.toList());
        List<FoodDto> foodDtoList = new ArrayList<>();

        collect.stream().map((list) -> {
            foodDtoList.add(foodtvrelationService.getByIdFood(list.longValue()));
            return foodDtoList;
        }).collect(Collectors.toList());

        balanceDto.setFoodDto(foodDtoList);
        return balanceDto;
    }

    /**
     * 查询所有方案 , 已复查
     *
     * @param page
     * @param pageSize
     * @param planName
     * @return
     */
    @Override
    public Page<Balance> getAllBalance(int page, int pageSize, String planName) {

        /**
         * 查询方案都需要哪些表来运作
         * 1 . balance表基础
         * 2 . food表
         * 3 . 维生素和微量元素
         */
        //构造分页构造器
        Page<Balance> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Balance> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(planName), Balance::getPlanName, planName);
        //添加排序条件
        queryWrapper.orderByDesc(Balance::getUpdateTime);

        //执行查询
        balanceService.page(pageInfo, queryWrapper);

        return pageInfo;
    }

    /**
     * 智能推荐
     *
     * @return
     */
    @Override
    public List<Balance> recommendAi() {

        // 发现没get的东西
        // LambdaQueryWrapper<Balance> queryWrapper = new LambdaQueryWrapper();
        // queryWrapper.orderByDesc(Balance::get)
        return null;
    }
}